<template>
	<view>
		<view class="address-wrapper" @click="getAddr">
			<view class="address" v-if="address.userName">
				<view class="receiver">
					<view class="name">收货人：{{address.userName}}</view>
					<view class="phone-num">{{address.telNumber}}</view>
					<text class="iconfont icon-arrow-right"></text>
				</view>
				<view class="address-txt">收货地址：{{address.provinceName+address.cityName+address.countyName+address.detailInfo}}</view>
			</view>
			<!-- 选择地址 -->
			<view class="choose-address" v-else>
				<view>请选择地址</view>
				<text class="iconfont icon-arrow-right"></text>
			</view>
			<view class="flower">
				<image src="/static/images/cart_border@2x.png">
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-list">
			<view class="goods-item" v-for="(item, index) in goodsList" :key="index">
				<image :src="item.goods_small_logo" alt="" />
				<view class="right">
					<text class="text-line2">{{item.goods_name}}</text>
					<view class="btm">
						<text class="price">￥<text>{{item.goods_price}}</text>.00</text>
						<view class="goods-num">
							<text>{{item.num}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="bottom-fixed" @click="pay">
			微信支付({{totalPrice}}.00)
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 用户的收货地址
				address: uni.getStorageSync('addr') || {},
				goodsList: []
			}
		},
		onLoad(options) {
			this.goodsId = parseInt(options.goodsId)
			this.queryGoodsList()
		},
		computed: {
			totalPrice() {
				// 总价格=所有勾选的商品数量*商品价格之和
				return this.goodsList.reduce((sum, item) => {
					return sum + item.num * item.goods_price
				}, 0)
			}
		},
		methods: {
			// 完成支付
			pay() {
				// 如果未选择收货地址
				if (!this.address) {
					uni.showToast({
						title: '请选择收货地址，再支付'
					})
					return
				}
				// this.token = uni.getStorageSync('token')

				// if (!this.token) {
				// 	// 跳转登录
				// 	uni.navigateTo({
				// 		url: '/pages/login/login'
				// 	})
				// }
				// 创建订单
				this.createOrder()
			},
			// 创建订单
			async createOrder() {
				let data = await this.$request({
					url: '/api/public/v1/my/orders/create',
					isAuth:true,
					method: 'POST',
					data: {
						order_price: this.totalPrice,
						consignee_addr: this.getConsigneeAddr(),
						goods: this.getFilterGoods()
					}
				})

				this.orderNumber = data.order_number
				// 获取支付参数,发起支付
				this.doPay()
				// 订单生成成功,如果不是从商详跳转，删除storage购物车已勾选的商品
				!this.goodsId&&this.$store.commit('arrangeCart')
			},
			// 获取支付参数,发起支付
			async doPay() {
				let data = await this.$request({
					url: '/api/public/v1/my/orders/req_unifiedorder',
					isAuth:true,//需要登陆态
					method: 'POST',
					data: {
						order_number: this.orderNumber
					}
				})
				// 唤起微信支付
				uni.requestPayment({
					...data.pay,
					success: () => {
						uni.showToast({
							title: '成功支付'
						})
						uni.navigateTo({
							url:'/pages/order_result/order_result'
						})
					},
					fail: () => {
						uni.showToast({
							title: '支付失败'
						})
						uni.navigateTo({
							url:'/pages/order_result/order_result?orderNumber='+this.orderNumber
						})
					}
				})
			},
			// 按具体字段返回goodsList
			getFilterGoods() {
				return this.goodsList.map(item => {
					return {
						goods_id: item.goodsId,
						goods_number: item.num,
						goods_price: item.goods_price
					}
				})
			},
			// 收货地址
			getConsigneeAddr() {
				let {
					provinceName,
					cityName,
					countyName,
					detailInfo,
					userName,
					telNumber
				} = this.address
				return provinceName + cityName + countyName + detailInfo + ` ${userName} ${telNumber}`
			},
			// 查询购物车中已勾选的商品列表
			async queryGoodsList() {
				//从商品详情点立即购买过来
				if (this.goodsId) {
					// 构造this.cart
					this.cart = [{
						goodsId: this.goodsId,
						num: 1,
						checked: true
					}]
				} else {
					this.cart = this.$store.getters.getCart
					// 过滤掉没有勾选的商品
					// 思路:遍历cart,如果元素checked为true,那么就添加goodsid;数据融合，还是得过滤this.cart
					// let idsArr =[]
					// this.cart.forEach(item=>{
					// 	if(item.checked){
					// 		idsArr.push(item.goodsId)
					// 	}
					// })

					// 过滤掉没有勾选的商品
					// 1.先过滤掉this.cart未勾选的商品
					this.cart = this.cart.filter(item => {
						return item.checked
					})
				}


				// 2. 再返回goodsId的数组
				let idsArr = this.cart.map(item => {
					return item.goodsId
				})
				let idsStr = idsArr.join(',')
				// 如果storage购物车为空,不请求
				if (!idsStr) {
					return
				}

				let _goodsList = await this.$request({
					url: '/api/public/v1/goods/goodslist?goods_ids=' + idsStr
				})

				// _goodsList是无序的
				//合并_goodslist和cart,以cart为主
				this.goodsList = this.cart.map(item => {
					// 在goodsList里面找一个对象的goodsId也等于item.goodsId
					let targetGoods = _goodsList.find(goods => {
						return goods.goods_id === item.goodsId
					})
					return { ...item,
						...targetGoods
					}
				})
			},
			// 同步微信的通讯地址
			getAddr() {
				// 发起授权
				uni.authorize({
					scope: 'scope.address',
					success: () => {
						// 调接口拿数据
						uni.chooseAddress({
							success: (addrRes) => {
								this.address = addrRes
								// 获取到address存储
								uni.setStorageSync('addr', this.address)
							}
						})
					},
					// 如果授权拒绝,或者拒绝再点击
					fail: () => {
						// 提示打开设置允许
						uni.showModal({
							title: '请在打开的设置中允许通讯地址',
							success: (res) => {
								// 用户点击确定
								if (res.confirm) {
									uni.openSetting()
								}
							}
						})
					}
				})
			}
		}
	}
</script>

<style lang="less">
	.address-wrapper {
		background-color: #fff;
	}

	.address {
		display: flex;
		flex-direction: column;
		padding: 44rpx 30rpx 48rpx 20rpx;

		.receiver {
			display: flex;
			justify-content: space-between;
			margin-bottom: 50rpx;
			position: relative;

			.phone-num {
				margin-right: 40rpx;
			}

			.icon-arrow-right {
				position: absolute;
				top: 8rpx;
				right: 0;
				color: #999;
			}
		}
	}

	.choose-address {
		display: flex;
		padding: 44rpx 30rpx 48rpx 20rpx;
		justify-content: space-between;

		.icon-arrow-right {
			color: #999;
		}
	}

	.flower {
		image {
			height: 16rpx;
			width: 100%;
			display: block;
		}
	}

	.goods-item {
		height: 206rpx;
		background-color: #fff;
		border-top: 1rpx solid #ddd;
		display: flex;
		box-sizing: border-box;
		align-items: center;

		image {
			width: 160rpx;
			height: 160rpx;
			margin-left: 30rpx;
		}

		.right {
			flex: 1;
			display: flex;
			flex-direction: column;
			margin: 0 20rpx 0 18rpx;

			.btm {
				display: flex;
				margin-top: 40rpx;
				justify-content: space-between;

				.price {
					color: #eb4450;

					>text {
						font-size: 24px;
					}
				}

				.goods-num {
					display: flex;
					align-items: center;

					button {
						width: 60rpx;
						height: 50rpx;
						box-sizing: border-box;
						display: flex;
						justify-content: center;
						align-items: center;
						border: 4rpx solid #666;
					}

					text {
						margin: 0 30rpx;
					}
				}
			}
		}
	}

	.goods-list {
		position: absolute;
		bottom: 98rpx;
		top: 243rpx;
		width: 100%;
		overflow: auto;
		padding-bottom: 60rpx;
		background-color: #f4f4f4;
	}

	.bottom-fixed {
		position: absolute;
		height: 98rpx;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #1aad19;
		color: #fff;
		line-height: 98rpx;
		text-align: center;
	}
</style>
